package es.mllacer.qqsm.tasks;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import es.mllacer.qqsm.R;
import es.mllacer.qqsm.Scores;
import es.mllacer.qqsm.util.HighScoreList;
import es.mllacer.qqsm.util.Utils;

public class GetRemoteScoresTask extends AsyncTask<Void, Integer, Boolean> {

	private static final String HIGH_SCORES_URI = "http://soletaken.disca.upv.es:8080/CMU/rest/highscores";

	private static final int SERVICE_NOT_AVAILABLE = 0;

	private Activity activity = null;

	public GetRemoteScoresTask(Activity activity) {
		this.activity = activity;
	}

	@Override
	protected void onPreExecute() {
		// nothing to do
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		SharedPreferences settingsPrefs = activity.getSharedPreferences(
				Utils.SETTINGS_PREFERENCES, Context.MODE_PRIVATE);
		String name = settingsPrefs.getString(Utils.USER_PREFERENCE, "");

		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
		HttpConnectionParams.setSoTimeout(httpParams, 5000);

		HttpClient client = new DefaultHttpClient(httpParams);
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("name", name));

		HttpGet request = new HttpGet(HIGH_SCORES_URI + "?"
				+ URLEncodedUtils.format(pairs, "utf-8"));

		try {
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				InputStream stream = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(stream));
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				stream.close();

				String responseString = sb.toString();
				GsonBuilder builder = new GsonBuilder();
				Gson gson = builder.create();
				JSONObject json = new JSONObject(responseString);
				HighScoreList list = gson.fromJson(json.toString(),
						HighScoreList.class);
				((Scores) activity).setMapScores(list);
			}
		} catch (IOException e) {
			publishProgress(SERVICE_NOT_AVAILABLE);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return true;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		for (int v : values) {
			if (v == SERVICE_NOT_AVAILABLE) {
				Toast.makeText(activity.getApplicationContext(),
						R.string.scores_service_not_available,
						Toast.LENGTH_SHORT).show();
			}
		}
	}

}
